package com.tarena.lbs.coupon.aop;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.enums.PassportResultEnum;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class AuthAop {

    @DubboReference
    private UserApi userApi;

    @Pointcut("execution(public * com.tarena.lbs.coupon.controller.CouponController.pageList(..) )|| " +
            "execution(public * com.tarena.lbs.coupon.controller.CouponController.addCoupon(..) )|| " +
            "execution(public * com.tarena.lbs.coupon.controller.CouponController.detail(..) )||" +
            "execution(public * com.tarena.lbs.coupon.controller.CouponController.receiveList(..) )|| " +
            "execution(public * com.tarena.lbs.coupon.controller.CouponController.receiveDetail(..) )"
    )
    public void authCheck(){}

    @Before("authCheck()")
    public void beforeMethod(JoinPoint joinPoint) throws BusinessException {
        log.info("用户账号认证AOP执行"+joinPoint.getSignature().getName());
        // 1.查询后台用户数据
        UserPrinciple userPrinciple= AuthenticationContextUtils.get();
        if(userPrinciple==null){
            log.info("没有获取到用户信息为null");
            throw new BusinessException(PassportResultEnum.AUTH_FAILED.getCode(),PassportResultEnum.AUTH_FAILED.getMessage());
        }
        AdminDto adminDto=userApi.getAdminById(userPrinciple.getId());
        log.info("用户账号认证,{}",adminDto);
        if(adminDto==null || adminDto.getId()==null || adminDto.getId().equals("")){
            log.info("获取到的用户信息不完整");
            throw new BusinessException(PassportResultEnum.AUTH_FAILED.getCode(),PassportResultEnum.AUTH_FAILED.getMessage());
        }
        // 2.检验用户的类型是否为商家用户
        if(adminDto.getAccountType()!=1){
            log.info("用户类型不是商家用户");
            throw new BusinessException(PassportResultEnum.AUTH_FAILED.getCode(),PassportResultEnum.AUTH_FAILED.getMessage());
        }
        // 3.检验用户的状态是否为启用
        if(adminDto.getAccountStatus()!=0){
            log.info("用户状态不是启用");
            throw new BusinessException(PassportResultEnum.AUTH_FAILED.getCode(),PassportResultEnum.AUTH_FAILED.getMessage());
        }
//        //3.把商家id放在ThreadLocal中
//        userPrinciple.setWorkId(adminDto.getBusinessId());
//        log.info("用户账号认证AOP通过"+joinPoint.getSignature().getName());
    }

}
